//
//  WXDanMu.m
//  弹幕
//
//  Created by tianlong on 2018/12/27.
//  Copyright © 2018年 tianlong. All rights reserved.
//

#import "WXDanMu.h"
#import "WXDanMuCell.h"
#import "Masonry.h"
#import "WXDanMuHeader.h"
#import "UIView+WXAutoLayout.h"

#define RandomColor [UIColor colorWithRed:(arc4random_uniform(256) / 255.0) green:(arc4random_uniform(256) / 255.0) blue:(arc4random_uniform(256) / 255.0) alpha:1.0]
#define AnimatonDuration 1

@interface WXDanMu ()
@property (assign, nonatomic) DanMuDirection direction;
@property (strong, nonatomic) NSMutableArray *dataM;
@property (strong, nonatomic) NSMutableArray *bufferCells;
@property (strong, nonatomic) NSMutableArray *visibleCells;
@property (weak,   nonatomic) UIScrollView *contentView;
@property (assign, nonatomic) CGRect conInitF;
@end

@implementation WXDanMu
- (instancetype)initWithDanMuDirection:(DanMuDirection)direction {
    self = [super init];
    if (self) {
        self.direction = direction;
        UIScrollView *conView = [[UIScrollView alloc] init];
        conView.alpha = 1;
        conView.scrollEnabled = NO;
        [self addSubview:conView];
        self.contentView = conView;
        
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

- (void)layoutSubviews{
    [super layoutSubviews];
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.right.offset(0);
    }];
    CGSize conSize = self.direction == DanMuDirectionVertical ? CGSizeMake(0, self.bounds.size.height) : CGSizeMake(self.bounds.size.width, 0);
    self.contentView.contentSize = conSize;
}

#pragma mark - 插入弹幕
- (void)insertDanMuMessage:(WXDanMuMessage *)message {
    [self insertDanMuMessage:message atIndex:0];
}

- (void)insertDanMuMessage:(WXDanMuMessage *)message atIndex:(NSInteger)index {
    if (!message || !message.content || message.content.length <= 0) {
        NSLog(@"弹幕(实例或内容)不能为空!!!");
        return;
    }
    
    if(index < 0) {
        NSLog(@"弹幕插入的位置不能小于0");
        return;
    }
    
    if (index > self.dataM.count) {
        NSLog(@"弹幕插入的位置大于弹幕总条数");
        return;
    }
    
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(danMuRunLoop) object:nil];
    [self.dataM insertObject:message atIndex:index];
    [self danMuRunLoop];
}

#pragma mark - 循环弹幕
- (void)danMuRunLoop {
    [self insertDanMuViewWithMessage:self.dataM.firstObject];
    __weak typeof(self)selfWeak = self;
    [self setAnimationFinishedBlock:^{
        if (selfWeak.dataM.count > 1) {
            id obj = selfWeak.dataM.firstObject;
            [selfWeak.dataM removeObject:obj];
            [selfWeak.dataM insertObject:obj atIndex:selfWeak.dataM.count];
        }
    }];
    [self performSelector:@selector(danMuRunLoop) withObject:nil afterDelay:AnimatonDuration+1];
}

#pragma mark - 插入弹幕视图
- (void)insertDanMuViewWithMessage:(WXDanMuMessage *)msg {
    NSString *identifier = @"";
    WXDanMuCell *cell = [self dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[WXDanMuCell alloc] initWithDanMuMessage:msg identifier:identifier];
        cell.alpha = 0;
        [self.contentView addSubview:cell];
        [self.visibleCells addObject:cell];
    }
    else {
        if (![cell isDescendantOfView:self.contentView]) {
            [self.contentView addSubview:cell];
            [self.visibleCells addObject:cell];
            NSLog(@"我来自缓存池,我骄傲了吗~~~~~~!!!!!");
        }
    }
    
    cell.msg = msg;
    NSLog(@"msg.content=%@_isMyTeam=%@",msg.content,msg.isMyTeam?@"YES":@"NO");
    
    [self layoutIfNeeded];
    
    //计算弹幕尺寸
    UIFont *font        = [UIFont fontWithName:WXDanMuCellTitleLabelFontName size:self.AutoFitFontSize(WXDanMuCellTitleLabelFontSize)];
    font                = [UIFont fontPingFangSCWithSize:self.AutoFitFontSize(WXDanMuCellTitleLabelFontSize)];
    CGFloat titleLeftM  = [self cellTitleLeftMWithMessage:msg];
    CGSize textSize     = [cell getTextSize:msg.content font:font lineBreakMode:WXDanMuCellLabelLineBreakMode maxSize:CGSizeMake(self.contentView.width - titleLeftM - WXDanMuCellTitleLableLeftM, MAXFLOAT)];
    CGFloat cellH       = [self cellHeight];
    NSLog(@"cellH ===== %f",cellH);
    
    //计算滚动范围和移动距离
    CGSize contentSize      = self.contentView.contentSize;
    CGFloat contentSizeH    = contentSize.height;
    CGFloat offsetY         = self.contentView.contentOffset.y;
    CGFloat moveDistance    = cellH + WXDanMuCellMargin;
    contentSizeH            += moveDistance;
    offsetY                 += moveDistance;
    contentSize = CGSizeMake(contentSize.width, contentSizeH);
    self.contentView.contentSize = contentSize;
    
    //布局弹幕cell
    CGFloat cellY = contentSizeH - moveDistance;
    CGFloat cellX = 0;
    CGFloat cellW = textSize.width+titleLeftM+WXDanMuCellTitleLableLeftM;
    [cell mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left   .offset(cellX);
        make.top    .offset(cellY);
        make.width  .offset(cellW);
        make.height .offset(cellH);
    }];
    [cell updateLayout];
    cell.layer.cornerRadius = cellH * 0.5;
    cell.layer.masksToBounds = YES;
    
    __weak typeof(self)selfWeak = self;
    [UIView animateWithDuration:AnimatonDuration animations:^{
        [selfWeak.contentView setContentOffset:CGPointMake(0, offsetY)];
        cell.alpha = 1;
    }completion:^(BOOL finished) {
        if (selfWeak.animationFinishedBlock) {
            selfWeak.animationFinishedBlock();
        }
        [selfWeak.visibleCells enumerateObjectsUsingBlock:^(WXDanMuCell *visCell, NSUInteger idx, BOOL * _Nonnull stop) {
            CGRect convertF = [selfWeak.contentView convertRect:visCell.frame toView:self];
            CGFloat cellMaxY = CGRectGetMaxY(convertF);
            /*
             * 出了可视范围,移入缓存池
             * cellH*3: 超出3个cell高度的时候在收入缓存池(原因:当弹幕快速插入时,由于弹幕插入的动画有淡入效果,若设置为边界=0,则会出现cell未到顶部就消失的错觉)
             */
            if (cellMaxY <= -cellH*3) {
                [visCell removeFromSuperview];
                [selfWeak.visibleCells removeObject:visCell];
                [selfWeak.bufferCells addObject:visCell];
                NSLog(@"哎呀, 不好, 一不小心滚出屏幕外了 === %@",visCell.msg.content);
            }
        }];
    }];
}

- (WXDanMuCell *)dequeueReusableCellWithIdentifier:(NSString *)idf {
    __block WXDanMuCell *cell = nil;
    __weak typeof(self)selfWeak = self;
    [self.bufferCells enumerateObjectsUsingBlock:^(WXDanMuCell *bufferCell, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([bufferCell.identifier isEqualToString:idf]) {
            [selfWeak.bufferCells removeObject:bufferCell];
            cell = bufferCell;
            *stop = YES;
        }
    }];
    return cell;
}

#pragma mark - lazyLoad
- (NSMutableArray *)dataM {
    if (!_dataM) {
        _dataM = [NSMutableArray array];
    }
    return _dataM;
}

- (NSMutableArray *)bufferCells {
    if (!_bufferCells) {
        _bufferCells = [NSMutableArray array];
    }
    return _bufferCells;
}

- (NSMutableArray *)visibleCells {
    if (!_visibleCells) {
        _visibleCells = [NSMutableArray array];
    }
    return _visibleCells;
}

#pragma mark - 计算视图高度
- (CGFloat)getViewHWithVisibleRows:(NSInteger)visibleRows {
    CGFloat cellH = [self cellHeight];
    CGFloat viewH = (cellH + WXDanMuCellMargin) * visibleRows;
    return viewH;
}

- (CGFloat)cellHeight{
    CGFloat titleTopM = [self cellTitleTopM];
    CGFloat cellH = ceilf(self.AutoFitHeight(WXDanMuCellTitleLabelHeight)+titleTopM*2);
    return cellH;
}

- (CGFloat)cellTitleTopM {
    CGFloat titleTopM   = ceilf(self.AutoFitTop(WXDanMuCellTitleLabelTopM));
    return titleTopM;
}

- (CGFloat)cellTitleLeftMWithMessage:(WXDanMuMessage *)msg {
    CGFloat leftM = msg.isMyTeam ? self.AutoFitWidth(WXDanMuCellHasHeadLableLeftM) : WXDanMuCellTitleLableLeftM;
    return leftM;
}

- (void)dealloc {
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
}

@end
